package com.zues.thread.lock.exercise;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;

/**
 * 转账案例，模拟转账操作
 * 有两个账户同时转钱，保证他们转账之后的金额总数不变
 * 这个时候会有两个账户的钱都是共享变量，都需要保护！
 * 临时的解决方案为上类锁
 * @author zues
 * @date 2019/03/06
 */
@Slf4j(topic = "c.ExerciseTransfer")
public class ExerciseTransfer {

    public static void main(String[] args) throws InterruptedException {
        Account a = new Account(1000);
        Account b = new Account(1000);
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                a.transfer(b, randomAmount());
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                b.transfer(a, randomAmount());
            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        //查看转账2000次后的总金额
        log.info("转账后总金额 = {}", a.getMoney() + b.getMoney());

    }



    //Random 为线程安全
    static Random random = new Random();

    //随机 1~100
    private static int randomAmount() {
        return random.nextInt(100) + 1;
    }
}

//账户
class Account {

    private int money;

    public Account(int money) {
        this.money = money;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    /**
     * 转账
     * @param target 目标账户
     * @param amount 金额
     */
    public void transfer(Account target, int amount) {
        //由于有多个共享资源需要上锁，临时方案先上类锁
        synchronized (Account.class) {
            if (this.money >= amount) {
                this.setMoney(this.money - amount);
                target.setMoney(target.money + amount);
            }
        }
    }
}
